import md5 from './SET_MD5_FUN';

import store from "@/store";

import commonConfigs from "./BASE_CONFIG"; // 项目基本配置

function getSortFun(data) {
	const inSortObj = {};
	
	for (const item of Object.keys(data).sort()) {
		inSortObj[item] = data[item]
	}

	return inSortObj;
}

export function setSignFun(params) {
	params.data = params.data || {};
	
	if(params.data.sign) delete params.data.sign;
	if (store.getters.userInfo && store.getters.userInfo.id) {
		params.data.uid = store.getters.userInfo.id;
	}
	
	params.data.time = params.data.time || (new Date()).getTime();
	params.data.pack_name = commonConfigs.appPackageName;
	params.data.version = commonConfigs.appPackageVer;
	params.data.platform = uni.getSystemInfoSync().platform;

	// #ifdef MP-WEIXIN
	let currentAppID = uni.getAccountInfoSync ? uni.getAccountInfoSync().miniProgram.appId : '';
	if (currentAppID) {
		params.data.appid = currentAppID;
	}
	// #endif
	// #ifdef APP-PLUS
	if (commonConfigs && commonConfigs.wechatOpenAppId) {
		params.data.appid = commonConfigs.wechatOpenAppId;
	}
	// #endif
	
	// #ifdef APP-PLUS
	params.data.isSimulator = plus.navigator.isSimulator();
	// #endif
	
	// #ifdef APP-PLUS
	if(store.getters.commonDeviceInfo) {
		store.getters.commonDeviceInfo.idfa && (params.data.idfa = store.getters.commonDeviceInfo.idfa);
		store.getters.commonDeviceInfo.duid && (params.data.duid = store.getters.commonDeviceInfo.duid);
		store.getters.commonDeviceInfo.oaid && (params.data.oaid = store.getters.commonDeviceInfo.oaid);
		store.getters.commonDeviceInfo.imei && (params.data.imei = store.getters.commonDeviceInfo.imei);
		store.getters.commonDeviceInfo.imsi && (params.data.imsi = store.getters.commonDeviceInfo.imsi);
		store.getters.commonDeviceInfo.uuid && (params.data.uuid = store.getters.commonDeviceInfo.uuid);
	}
	// #endif
	
	const sortKeyList = Object.keys(params.data).sort();
	for (const item in sortKeyList) {
		const value = params.data[sortKeyList[item]];
		if(
			value === undefined || 
			value === "undefined" ||
			value === null ||
			value === "null" ||
			value === ""
		) {
			delete params.data[sortKeyList[item]]
		}
	}
	
	const {
		method,
		data
	} = params;

	if (['get', 'GET'].includes(method)) {
		for (const item in data) {
			const value = data[item];
			if (!isNaN(+value)) {
				data[item] = `${data[item]}`
			}
		}
	}
	
	let inSortObj = getSortFun(data);
	let firstSignVal = md5(JSON.stringify(inSortObj) + data.time + unescape(commonConfigs.signingKeyStr));
	let secondSignVal = md5(firstSignVal);
	data.sign = secondSignVal + firstSignVal;
	
	return params;
}